package com.mingweicai.intergration.redis.sentinel;

import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisSentinelPool;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Transaction;

//@Component
public class RedisHelper {

  @Autowired
  private JedisSentinelPool jedisSentinelPool;

  void set(String key , String value){

    Jedis jedis = null;
    try {
      jedis = jedisSentinelPool.getResource();
      jedis.set(key,value);
    }catch (Exception ex){

    }finally {
      if(jedis != null){
        jedis.close();
      }
    }
  }

  void batchDel(String...keys){
    Jedis jedis = null;
    try {
      jedis = jedisSentinelPool.getResource();
      Pipeline pipeline = jedis.pipelined();
      for(String key : keys){
        jedis.del(key);
      }
      pipeline.sync();
    }finally {
      if(jedis != null){
        jedis.close();
      }
    }
  }

  void batchDelWithResult(String...keys){
    Jedis jedis = null;
    try {
      jedis = jedisSentinelPool.getResource();
      Pipeline pipeline = jedis.pipelined();
      for(String key : keys){
        jedis.del(key);
      }
      List<Object> result = pipeline.syncAndReturnAll();
      for (Object object : result) {
        System.out.println(object);
      }
    }finally {
      if(jedis != null){
        jedis.close();
      }
    }
  }

  void transactionProccess(String key){
    Jedis jedis = null;
    try {
      jedis = jedisSentinelPool.getResource();
      // watch
      jedis.watch(key);
      // 开启事务
      Transaction tx = jedis.multi();
      // 处理
      List<Object> response = tx.exec();
      System.out.println("response: "+ response);

    }finally {
      if(jedis != null){
        jedis.close();
      }
    }
  }

  public void eval(){
    Jedis jedis = jedisSentinelPool.getResource();
    try {
      String lua = "local num = redis.call('incr', KEYS[1])\n" +
          "if tonumber(num) == 1 then\n" +
          "\tredis.call('expire', KEYS[1], ARGV[1])\n" +
          "\treturn 1\n" +
          "elseif tonumber(num) > tonumber(ARGV[2]) then\n" +
          "\treturn 0\n" +
          "else \n" +
          "\treturn 1\n" +
          "end\n";
      Object result = jedis.evalsha(jedis.scriptLoad(lua), Arrays.asList("localhost"), Arrays.asList("10", "2"));
      System.out.println(result);
    }catch (Exception e){
      e.printStackTrace();
    }finally {
      if(jedis != null){
        try {
          jedis.close();
        }catch (Exception e){
          e.printStackTrace();
        }
      }
    }
  }

}
